//
//  ScanBleViewController.m
//  SITABLE
//
//  Created by songjun on 16/9/21.
//  Copyright © 2016年 Sita. All rights reserved.
//

#import "ScanBleViewController.h"

@interface ScanBleViewController ()

@end

@implementation ScanBleViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil options:nil];
    
    
    scanBaby = [BabyBluetooth shareBabyBluetooth];
    [self babyDelegate];
    scanBaby.scanForPeripherals().begin().stop(5);
    peripheralsArr = [NSMutableArray arrayWithCapacity:1];
    
   
    [self performSelector:@selector(dismissHud1302) withObject:nil afterDelay:5.0];
    
//    UIButton *freshBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    freshBtn.frame = CGRectMake(0, 0, 40, 40);
//    [freshBtn setTitle:@"刷新" forState:UIControlStateNormal];
//    [freshBtn addTarget:self action:@selector(freshBtnAction:) forControlEvents:UIControlEventTouchUpInside];
//    freshBtn.titleLabel.font = linBoardFont15;
//    UIBarButtonItem *rightBtnItem = [[UIBarButtonItem alloc] initWithCustomView:freshBtn];
//    self.navigationItem.rightBarButtonItem = rightBtnItem;
    
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    MBProgressHUD *hud = [[MBProgressHUD alloc] initWithWindow:window];
    hud.labelText = @"扫描......";
    hud.tag = 1302;
    [window addSubview:hud];
    [hud show:YES];
    
    //-(CBCentralManager *)centralManager;
    
//    UIButton *disconnetBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    disconnetBtn.frame = CGRectMake(SCREEN_WIDTH/2-40/2, 0, 40, 40);
//    [disconnetBtn setTitle:@"断开" forState:UIControlStateNormal];
//    [disconnetBtn addTarget:self action:@selector(disconnetBtnAction:) forControlEvents:UIControlEventTouchUpInside];
//    [self.navigationController.navigationBar addSubview:disconnetBtn];
    
    baseTablevie.backgroundColor = UIColorHexRGBA(linBoardBGGrayColor, 1.0);
    self.view.backgroundColor = UIColorHexRGBA(linBoardBGGrayColor, 1.0);
    baseTablevie.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0)];
    
}

-(void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    //第一次打开或者每次蓝牙状态改变都会调用这个函数
    if(central.state==CBCentralManagerStatePoweredOn)
    {
        NSLog(@"蓝牙设备开着");
        //self.blueToothOpen = YES;
    }
    else
    {
        NSLog(@"蓝牙设备关着");
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"蓝牙设备关闭" message:@"请在设置里开启蓝牙" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
        
    }
}

-(void)disconnetBtnAction:(UIButton *)btn
{
    [scanBaby cancelPeripheralConnection:selectedPeripheral];
}

-(void)dismissHud1302
{
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    MBProgressHUD *hud = [window viewWithTag:1302];
    if (hud!=nil) {
        [hud removeFromSuperview];
    }
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    [scanBaby cancelScan];
}

-(void)freshBtnAction:(UIButton *)btn
{
    
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    MBProgressHUD *hud = [[MBProgressHUD alloc] initWithWindow:window];
    hud.labelText = @"扫描......";
    hud.tag = 1302;
    [window addSubview:hud];
    [window bringSubviewToFront:hud];
    [hud show:YES];
    
    [self performSelector:@selector(dismissHud1302) withObject:nil afterDelay:5.0];

    
    //NSLog(@"***:%@",hud);
    //[scanBaby cancelScan];
    scanBaby = [BabyBluetooth shareBabyBluetooth];
    
    [self babyDelegate];
    [peripheralsArr removeAllObjects];
    [baseTablevie reloadData];
    scanBaby.scanForPeripherals().begin().stop(5);
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

-(void)babyDelegate{
    //设置扫描到设备的委托
    __block ScanBleViewController *myself = self;
    [scanBaby setBlockOnDiscoverToPeripherals:^(CBCentralManager *central, CBPeripheral *peripheral, NSDictionary *advertisementData, NSNumber *RSSI) {
        NSLog(@"****:%@",peripheral.name);
        if ([peripheral.name hasPrefix:FilterBleName]) {
             [myself->peripheralsArr addObject:peripheral];
        }
    }];
    
    
    [scanBaby setBlockOnCancelScanBlock:^(CBCentralManager *centralManager) {
        [myself dismissHud1302];
        [myself->baseTablevie reloadData];
    }];
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return peripheralsArr.count;
    //return 10;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identify = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identify];
    if (cell == nil) {
        cell= [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identify];
    }
    CBPeripheral *perp = [peripheralsArr objectAtIndex:indexPath.row];
    cell.textLabel.text = [NSString stringWithFormat:@"%@",perp.name];
    //cell.textLabel.text = [NSString stringWithFormat:@"%ld",indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    CBPeripheral *peripheral = [peripheralsArr objectAtIndex:indexPath.row];
    selectedPeripheral = peripheral;
    [[NSUserDefaults standardUserDefaults] setValue:peripheral.name forKey:@"linboardPName"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    scanBaby.having(peripheral).connectToPeripherals().discoverServices().discoverCharacteristics()
    .readValueForCharacteristic().discoverDescriptorsForCharacteristic().readValueForDescriptors().begin();
    
    __block ScanBleViewController *myself = self;
    //设置读取characteristics的委托
    [scanBaby setBlockOnReadValueForCharacteristic:^(CBPeripheral *peripheral, CBCharacteristic *characteristics, NSError *error) {
        NSLog(@"characteristic name:%@ value is:%@",characteristics.UUID,characteristics.value);
        if ([characteristics.UUID.description isEqualToString:@"FFE1"]) {
            // NSLog(@"sdfasdfasdfasdfds");
            myCharactertistic =characteristics;
            
            if (!myself->getBlePwdTimer) {
                getBlePwdTimer= [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(getBlePwdTimer) userInfo:nil repeats:YES];
            }else{
                [myself->getBlePwdTimer resumeTimer];
            }
            
            //注册特征值监听回调
            [myself->scanBaby notify:peripheral characteristic:characteristics block:^(CBPeripheral *peripheral, CBCharacteristic *characteristics, NSError *error) {
                //NSLog(@"%@",characteristics.value);
                NSString *result  = [myself convertDataToHexStr:characteristics.value];
                //NSLog(@"回调:::%@",result);
                if ([result hasPrefix:linboardPWDResponse]){
                    //保存密码:
                    [myself->getBlePwdTimer pauseTimer];
                    //linboardBlePassword
                    NSString *subString=[result substringFromIndex:linboardPWDResponse.length];
                    //NSLog(@"第一次截取:%@",subString);
                    NSString *sub1S = [subString substringToIndex:subString.length-4];
                    //NSLog(@"真正的密码:%@",sub1S);
                    [[NSUserDefaults standardUserDefaults] setValue:sub1S forKey:@"linboardBlePassword"];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                }
            }];
        }
    }];
    
    //断开自动重连
    [scanBaby setBlockOnDisconnect:^(CBCentralManager *central, CBPeripheral *peripheral, NSError *error) {
        // NSLog(@"设备：%@--断开连接",peripheral.name);
        [myself->scanBaby AutoReconnect:peripheral];
    }];
}


-(NSString *)convertDataToHexStr:(NSData *)data {
    if (!data || [data length] == 0) {
        return @"";
    }
    NSMutableString *string = [[NSMutableString alloc] initWithCapacity:[data length]];
    
    [data enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange, BOOL *stop) {
        unsigned char *dataBytes = (unsigned char*)bytes;
        for (NSInteger i = 0; i < byteRange.length; i++) {
            
            NSString *hexStr = [NSString stringWithFormat:@"%x", (dataBytes[i]) & 0xff];
            if ([hexStr length] == 2) {
                [string appendString:hexStr];
            } else {
                [string appendFormat:@"0%@", hexStr];
            }
        }
    }];
    return string;
}


-(void)getBlePwdTimer
{
    NSString *linboardGetBlePwd =linboardSearchPwdString;
    NSData *transData = [linboardGetBlePwd hexToBytes];
    if (selectedPeripheral!=nil&&myCharactertistic!=nil) {
        [selectedPeripheral writeValue:transData forCharacteristic:myCharactertistic type:CBCharacteristicWriteWithoutResponse];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (IBAction)freshCarBtnAction:(UIButton *)sender
{
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    MBProgressHUD *hud = [[MBProgressHUD alloc] initWithWindow:window];
    hud.labelText = @"扫描......";
    hud.tag = 1302;
    [window addSubview:hud];
    [window bringSubviewToFront:hud];
    [hud show:YES];
    
    [self performSelector:@selector(dismissHud1302) withObject:nil afterDelay:5.0];
    
    scanBaby = [BabyBluetooth shareBabyBluetooth];
    
    [self babyDelegate];
    [peripheralsArr removeAllObjects];
    [baseTablevie reloadData];
    scanBaby.scanForPeripherals().begin().stop(5);

}
@end
